import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:excel/excel.dart';
import 'package:csv/csv.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import '../models/check_in_record.dart';
import '../repositories/check_in_record_repository.dart';
import '../repositories/check_in_goal_repository.dart';

class CheckInExportService {
  final CheckInRecordRepository _recordRepository = CheckInRecordRepository();
  final CheckInGoalRepository _goalRepository = CheckInGoalRepository();
  
  /// 导出签到记录为CSV文件
  Future<String> exportToCsv() async {
    try {
      // 获取所有签到记录
      final records = await _recordRepository.getAllCheckInRecords();
      if (records.isEmpty) {
        return "没有签到记录可导出";
      }
      
      // 获取所有目标
      final goals = await _goalRepository.getAllCheckInGoals();
      final goalMap = {for (var goal in goals) goal.id: goal};
      
      // 准备CSV数据
      List<List<dynamic>> csvData = [];
      
      // 添加表头
      List<dynamic> header = [
        '日期',
        '学习时长(分钟)',
        '学习单词数',
        '答题数量',
        '备注',
      ];
      
      // 添加目标列
      for (var goal in goals) {
        header.add('${goal.title}(${goal.unit})');
      }
      
      csvData.add(header);
      
      // 添加数据行
      for (var record in records) {
        final date = DateTime.fromMillisecondsSinceEpoch(record.date);
        final dateStr = DateFormat('yyyy-MM-dd').format(date);
        
        List<dynamic> row = [
          dateStr,
          record.studyTime,
          record.wordsLearned,
          record.questionsAnswered,
          record.note,
        ];
        
        // 添加目标进度
        for (var goal in goals) {
          final goalId = goal.id;
          if (goalId != null && record.goalProgress.containsKey(goalId)) {
            row.add(record.goalProgress[goalId]);
          } else {
            row.add(0);
          }
        }
        
        csvData.add(row);
      }
      
      // 转换为CSV字符串
      String csv = const ListToCsvConverter().convert(csvData);
      
      // 保存到文件
      String dirPath;
      final now = DateTime.now();
      final timestamp = DateFormat('yyyyMMdd_HHmmss').format(now);
      
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        // 桌面平台使用固定路径
        dirPath = 'D:\\000\\my-web\\学习宝库\\签到';
        // 确保目录存在
        final directory = Directory(dirPath);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
      } else {
        // 移动平台使用Download/考试宝目录
        try {
          // 请求存储权限
          var status = await Permission.storage.request();
          if (!status.isGranted) {
            throw Exception('需要存储权限才能导出文件');
          }
          
          // 获取外部存储目录
          final directory = await getExternalStorageDirectory();
          if (directory == null) {
            throw Exception('无法获取外部存储目录');
          }
          
          // 获取Download目录 - 内部存储
          final downloadDir = Directory('${directory.path.split('Android')[0]}Download/考试宝/签到');
          dirPath = downloadDir.path;
          
          // 确保目录存在
          if (!await downloadDir.exists()) {
            await downloadDir.create(recursive: true);
          }
        } catch (e) {
          print('设置移动平台导出路径失败: $e');
          throw Exception('设置导出路径失败: $e');
        }
      }
      
      final path = '$dirPath/签到记录_$timestamp.csv';
      final File file = File(path);
      await file.writeAsString(csv);
      
      return path;
    } catch (e) {
      return "导出失败: $e";
    }
  }
  
  /// 导出签到记录为Excel文件
  Future<String> exportToExcel() async {
    try {
      // 获取所有签到记录
      final records = await _recordRepository.getAllCheckInRecords();
      if (records.isEmpty) {
        return "没有签到记录可导出";
      }
      
      // 获取所有目标
      final goals = await _goalRepository.getAllCheckInGoals();
      final goalMap = {for (var goal in goals) goal.id: goal};
      
      // 创建Excel文档
      final excel = Excel.createExcel();
      final Sheet sheet = excel['签到记录'];
      
      // 添加表头
      List<String> header = [
        '日期',
        '学习时长(分钟)',
        '学习单词数',
        '答题数量',
        '备注',
      ];
      
      // 添加目标列
      for (var goal in goals) {
        header.add('${goal.title}(${goal.unit})');
      }
      
      // 写入表头
      for (var i = 0; i < header.length; i++) {
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: i, rowIndex: 0)).value = header[i];
      }
      
      // 添加数据行
      for (var i = 0; i < records.length; i++) {
        final record = records[i];
        final date = DateTime.fromMillisecondsSinceEpoch(record.date);
        final dateStr = DateFormat('yyyy-MM-dd').format(date);
        
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: i + 1)).value = dateStr;
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: i + 1)).value = record.studyTime;
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: i + 1)).value = record.wordsLearned;
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 3, rowIndex: i + 1)).value = record.questionsAnswered;
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 4, rowIndex: i + 1)).value = record.note;
        
        // 添加目标进度
        for (var j = 0; j < goals.length; j++) {
          final goalId = goals[j].id;
          if (goalId != null && record.goalProgress.containsKey(goalId)) {
            sheet.cell(CellIndex.indexByColumnRow(columnIndex: 5 + j, rowIndex: i + 1)).value = record.goalProgress[goalId];
          } else {
            sheet.cell(CellIndex.indexByColumnRow(columnIndex: 5 + j, rowIndex: i + 1)).value = 0;
          }
        }
      }
      
      // 保存到文件
      String dirPath;
      final now = DateTime.now();
      final timestamp = DateFormat('yyyyMMdd_HHmmss').format(now);
      
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        // 桌面平台使用固定路径
        dirPath = 'D:\\000\\my-web\\学习宝库\\签到';
        // 确保目录存在
        final directory = Directory(dirPath);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
      } else {
        // 移动平台使用Download/考试宝目录
        try {
          // 请求存储权限
          var status = await Permission.storage.request();
          if (!status.isGranted) {
            throw Exception('需要存储权限才能导出文件');
          }
          
          // 获取外部存储目录
          final directory = await getExternalStorageDirectory();
          if (directory == null) {
            throw Exception('无法获取外部存储目录');
          }
          
          // 获取Download目录 - 内部存储
          final downloadDir = Directory('${directory.path.split('Android')[0]}Download/考试宝/签到');
          dirPath = downloadDir.path;
          
          // 确保目录存在
          if (!await downloadDir.exists()) {
            await downloadDir.create(recursive: true);
          }
        } catch (e) {
          print('设置移动平台导出路径失败: $e');
          throw Exception('设置导出路径失败: $e');
        }
      }
      
      final path = '$dirPath/签到记录_$timestamp.xlsx';
      final File file = File(path);
      await file.writeAsBytes(excel.encode()!);
      
      return path;
    } catch (e) {
      return "导出失败: $e";
    }
  }
}